package com.css.dzj.zfjg.modules.admpunishment.controller;


import com.css.aq.server.service.BaseService;
import com.css.dzj.zfjg.common.exception.CvaException;
import com.css.dzj.zfjg.common.util.BeanUtil;
import com.css.dzj.zfjg.common.util.CvaConstants;
import com.css.dzj.zfjg.common.util.R;
import com.css.dzj.zfjg.modules.admpunishment.service.JgJgxwPunishActionService;
import com.css.dzj.zfjg.modules.admpunishment.entity.JgJgxwPunishActionEntity;
import com.querydsl.core.QueryResults;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.*;


/**
 * 行政处罚行为信息
 *
 * @author chenshun
 * @email sunlightcs@gmail.com
 * @date 2019-10-31 11:40:26
 */
@RestController
@RequestMapping("jgxw/jgjgxwpunishaction")
public class JgJgxwPunishActionController {
    @Autowired
    private JgJgxwPunishActionService jgJgxwPunishActionService;

    @Autowired
    private BaseService baseService;

    /**
     * 列表
     */
    @RequestMapping("/list")
    public R list(@RequestParam(name = "pageSize" ,required = false)Integer pageSize,
                  @RequestParam(name = "pageNo" ,required = false)Integer pageNo){
        try {
            PageRequest pageRequest = PageRequest.of(pageNo-1, pageSize);
            QueryResults page = jgJgxwPunishActionService.queryPage(pageRequest);
            baseService.logSuccess(3, "分页查询行政处罚行为成功", "2");
            return R.ok().put("page", page);
        } catch (Exception e) {
            e.printStackTrace();
            baseService.logFailed(3, "分页查询行政处罚行为失败", "2");
            return R.error(e.getMessage());
        }

    }


    /**
     * 信息
     */
    @RequestMapping("/info")
    public R info(String id){
        try {
            if(StringUtils.isNotEmpty(id)){
                JgJgxwPunishActionEntity jgJgxwPunishAction = jgJgxwPunishActionService.getById(id);
                baseService.logSuccess(3, "查看行政处罚行为详情成功", "2");
                return R.ok().put("jgJgxwPunishAction", jgJgxwPunishAction);
            }else {
                baseService.logFailed(3, "查看行政处罚行为详情失败", "2");
                return R.error("id不能为空");
            }
        } catch(Exception e) {
            e.printStackTrace();
            baseService.logFailed(3, "查看行政处罚行为详情失败", "2");
            return R.error(e.getMessage());
        }

    }

    /**
     * 保存
     */
    @RequestMapping("/save")
    public R addPunishAction(@RequestBody JgJgxwPunishActionEntity jgJgxwPunishActionEntity, HttpServletRequest request){
        //jgJgxwPunishActionEntity.setId(UuidUtil.getUuid());
        //用户字段
       /* SysUserEntity userEntity = (SysUserEntity)request.getSession().getAttribute("user");
        jgJgxwPunishActionEntity.setCurrentuserid(userEntity.getUserId());
        //记录唯一标识
        jgJgxwPunishActionEntity.setRecordUniqueIdentity(UuidUtil.getUuid());*/
        //创建人
       /* if(StringUtils.isNotEmpty(userEntity.getUserId())){
            jgJgxwPunishActionEntity.setCreateUser(userEntity.getUserId());
        }*/
        //前台调中台接口，直接传编码
      /*  String areaNumber = jgJgxwPunishActionEntity.getAreaNumber();
        if(StringUtils.isNotEmpty(areaNumber)){
            if(StringUtils.isNotEmpty(areaUtils.getCodeByName(areaNumber))){
                jgJgxwPunishActionEntity.setAreaNumber(areaUtils.getCodeByName(areaNumber));
            }
        }
        //cd_id
        jgJgxwPunishActionEntity.setCdId(UuidUtil.getUuid());*/

        Date now = Calendar.getInstance().getTime();
        jgJgxwPunishActionEntity.setCdTime(now);
        //新增数据类型i-insert,u-update,d-delete
        jgJgxwPunishActionEntity.setCdOperation(CvaConstants.INSERT_OPER_FLAG);
        //创建时间
        jgJgxwPunishActionEntity.setCreateTime(now);
        //flag
        jgJgxwPunishActionEntity.setFlag(CvaConstants.UN_DELETED_FLAG);
        //来源
        jgJgxwPunishActionEntity.setCdSource(CvaConstants.CD_SOURCE);
        //检查行为编码
        try{
            //检查行为编码
            String actionCode = jgJgxwPunishActionEntity.getCheckActionCode();
            if("无".equals(actionCode)){
                jgJgxwPunishActionService.save(jgJgxwPunishActionEntity);
                return R.ok("保存成功!");
            }
            jgJgxwPunishActionService.save(jgJgxwPunishActionEntity);
            baseService.logSuccess(3, "新增行政处罚行为成功", "2");
        }catch(CvaException e){
            e.printStackTrace();
            baseService.logFailed(3, "新增行政处罚行为失败", "2");
            return R.error("保存失败!");
        }
        return R.ok("保存成功!");
    }

    /**
     * 修改
     */
    @RequestMapping("/update")
    public R update(@RequestBody JgJgxwPunishActionEntity jgJgxwPunishAction, HttpServletRequest request){
        try {
            String id = jgJgxwPunishAction.getId();
            Date now = Calendar.getInstance().getTime();
            jgJgxwPunishAction.setGxsj(now);
            //新增数据类型i-insert,u-update,d-delete
            jgJgxwPunishAction.setCdOperation(CvaConstants.UPDATE_OPER_FLAG);
            //flag
            jgJgxwPunishAction.setFlag(CvaConstants.UN_DELETED_FLAG);
            //来源
            jgJgxwPunishAction.setCdSource(CvaConstants.CD_SOURCE);
            //修改时间
            jgJgxwPunishAction.setUpdateTime(now);
            JgJgxwPunishActionEntity jpae = jgJgxwPunishActionService.getById(id);
            BeanUtil.copyBeanNotNullToBean(jgJgxwPunishAction, jpae);
            baseService.logSuccess(3, "修改行政处罚行为成功", "2");
            return R.ok();
        } catch (Exception e) {
            e.printStackTrace();
            baseService.logFailed(3, "修改行政处罚行为失败", "2");
            return R.error(e.getMessage());
        }

    }

    /**
     * 删除
     */
    @RequestMapping("/delete")
    public R delete(@RequestBody Map<String, Object> params){
        List<String> uuids = (List<String>) params.get("uuids");
        if (uuids.size()>= 1 && uuids != null){
            for (String uuid : uuids) {
                //JgJgxwPunishActionEntity jgJgxwPunishAction = jgJgxwPunishActionService.getById(uuid);
                //jgJgxwPunishAction.setCdOperation(CvaConstants.DELETED_OPER_FLAG);
                jgJgxwPunishActionService.updateById(uuid);
            }
            baseService.logSuccess(3, "删除行政处罚行为成功", "2");
            return R.ok();
        }else {
            baseService.logFailed(3, "删除行政处罚行为失败", "2");
            return R.error();
        }
    }

    /*@RequestMapping("/dowloadExcel")
    public void dowloadExcel(HttpServletResponse response, HttpServletRequest request){

        DowloadExcelUtil.dowloadTemplate(response,request,"行政处罚行为信息");
    }*/

    /**
     * 导入
     */

    /*@RequestMapping("/importExcel")
    public R importExcel(@RequestParam MultipartFile file, HttpServletRequest request) throws ParseException {
        List<JgJgxwPunishActionEntity> JgJgxwPunishActionEntities = EasyPoiUtils.importExcel(file, 0, 1, JgJgxwPunishActionEntity.class);
        Integer errorRow = 1;
        String [] fileds = {"superviseItemCode", "punishActionName", "punishActionCode",
                "implementInstitution", "implementInstitutionCode", "entrustDept",
                "entrustDeptCode", "superviseObject", "caseSource", "checkActionCode",
                "administrativeCp", "administrativeCpNa", "administrativeCpCeType",
                "administrativeCpUiCode", "addressRegistered", "addressOperating",
                "areaNumber", "illegalFact", "punishAccord", "punishProcedure",
                "ifHearingWitnesses", "filingDate", "caseInvolvingPunishment",
                "majorCase", "legalReview", "galReviewDate", "legalReviewOpinions",
                "discussCollectively", "oupDiscussionDate", "groupDiscussionConclusion",
                "punishDocumentCode", "setDate", "punishType", "fine", "penaltyResult",
                "administrativeReconsider", "administrativeAction", "casesClosedExecutionWay",
                "casesClosedExecutionResult", "casesClosedFine", "casesClosedExecution",
                "administrativePenalties", "otherDisposals", "portationDate",
                "bmittedDate", "submittedPersonnel"};
        Integer flags[] = {1,1,1,0,0,0,0,1,1,1,1,1,1,1,0,0,1,1,1,1,1,1,1,1,1,0,0,1,0,0,1,1,1,0,1,1,1,1,1,0,1,1,0,0,0,1};

        for (int i = 0; i < JgJgxwPunishActionEntities.size(); i++) {
            JgJgxwPunishActionEntity jgJgxwPunishAction = JgJgxwPunishActionEntities.get(i);
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            SimpleDateFormat sdf1 = new SimpleDateFormat("EEE MMM dd HH:mm:ss zzz yyyy", Locale.ENGLISH);

            //数据验证
            String errorMsg = ExcelUtils.isMustFilled(jgJgxwPunishAction,fileds,flags);
            //确定第几行
            errorRow = i+2;
            if (StringUtils.isNotEmpty(errorMsg)){
                return R.error("导入失败，第" + errorRow +"行第"+ errorMsg+"列数据有误！");
            }else{
                //uuid
                jgJgxwPunishAction.setId(UuidUtil.getUuid());
                //用户字段
                SysUserEntity userEntity = (SysUserEntity) request.getSession().getAttribute("user");
                jgJgxwPunishAction.setCurrentuserid(userEntity.getUserId());
                //记录唯一标识
                jgJgxwPunishAction.setRecordUniqueIdentity(UuidUtil.getUuid());
                //新增数据类型i-insert,u-update,d-delete
                jgJgxwPunishAction.setCdOperation(CvaConstants.INSERT_OPER_FLAG);
                //插入时间
                Date now = Calendar.getInstance().getTime();
                jgJgxwPunishAction.setCdTime(now);
                //cd_id
                jgJgxwPunishAction.setCdId(UuidUtil.getUuid());
                //flag
                jgJgxwPunishAction.setFlag(CvaConstants.UN_DELETED_FLAG);
                //值转换编码
                HashMap<String, String> codeByValue = dictionaryService.findCodeByValue(jgJgxwPunishAction.getLawDepartment(), jgJgxwPunishAction.getLawOffice());
                jgJgxwPunishAction.setLawDepartment(codeByValue.get("lawDepartment"));
                jgJgxwPunishAction.setLawOffice(codeByValue.get("lawOffice"));
                jgJgxwPunishAction.setFlag(CvaConstants.UN_DELETED_FLAG);
                //行政区划代码，连内网，通过名称获取编码
                String areaNumber = jgJgxwPunishAction.getAreaNumber();
                if(StringUtils.isNotEmpty(areaNumber)){
                    if(StringUtils.isNotEmpty(areaUtils.getCodeByName(areaNumber))){
                        jgJgxwPunishAction.setAreaNumber(areaUtils.getCodeByName(areaNumber));
                    }
                }
                //jgJgxwPunishAction.setAreaNumber("123456");
                //来源，定死工信部
                jgJgxwPunishAction.setCdSource(CvaConstants.CD_SOURCE);
                //作出行政处罚日期
                if(StringUtils.isNotEmpty(jgJgxwPunishAction.getSetDate())){
                    String format1 = sdf.format(sdf1.parse(jgJgxwPunishAction.getSetDate()));
                    jgJgxwPunishAction.setSetDate(format1);
                }

                //处罚立案时间
                if(StringUtils.isNotEmpty(jgJgxwPunishAction.getFilingDate())){
                    String format2 = sdf.format(sdf1.parse(jgJgxwPunishAction.getFilingDate()));
                    jgJgxwPunishAction.setFilingDate(format2);
                }
                //结案情况—结案日期
                if(StringUtils.isNotEmpty(jgJgxwPunishAction.getAdministrativePenalties())){
                    String format3 = sdf.format(sdf1.parse(jgJgxwPunishAction.getAdministrativePenalties()));
                    jgJgxwPunishAction.setAdministrativePenalties(format3);
                }

                //行政相对人性质 xzxdrxz_status
                String administrativeCpNa = jgJgxwPunishAction.getAdministrativeCpNa();
                if (administrativeCpNa != null && !"".equals(administrativeCpNa)) {
                    Dictionary dictionary = dictionaryService.findCodeByTypeAndvalue("xzxdrxz_status", administrativeCpNa);
                    if (StringUtils.isNotEmpty(dictionary.getItemCode())) {
                        jgJgxwPunishAction.setAdministrativeCpNa(dictionary.getItemCode());
                    }
                }
                //行政相对人证件类型 zjlx_status
                String administrativeCpCeType = jgJgxwPunishAction.getAdministrativeCpCeType();
                if (administrativeCpCeType != null && !"".equals(administrativeCpCeType)) {
                    Dictionary dictionary = dictionaryService.findCodeByTypeAndvalue("zjlx_status", administrativeCpCeType);
                    if (StringUtils.isNotEmpty(dictionary.getItemCode())) {
                        jgJgxwPunishAction.setAdministrativeCpCeType(dictionary.getItemCode());
                    }
                }
                //处罚程序 cfcx_status
                String punishProcedure = jgJgxwPunishAction.getPunishProcedure();
                if (punishProcedure != null && !"".equals(punishProcedure)) {
                    Dictionary dictionary = dictionaryService.findCodeByTypeAndvalue("cfcx_status", punishProcedure);
                    if (StringUtils.isNotEmpty(dictionary.getItemCode())) {
                        jgJgxwPunishAction.setPunishProcedure(dictionary.getItemCode());
                    }
                }
                //处罚种类 cfzl_status
                String punishType = jgJgxwPunishAction.getPunishType();
                if (punishType != null && !"".equals(punishType)) {
                    Dictionary dictionary = dictionaryService.findCodeByTypeAndvalue("cfzl_status", punishType);
                    if (StringUtils.isNotEmpty(dictionary.getItemCode())) {
                        jgJgxwPunishAction.setPunishType(dictionary.getItemCode());
                    }
                }
                //行政复议 xzfy_status
                String administrativeReconsider = jgJgxwPunishAction.getAdministrativeReconsider();
                if (administrativeReconsider != null && !"".equals(administrativeReconsider)) {
                    Dictionary dictionary = dictionaryService.findCodeByTypeAndvalue("xzfy_status", administrativeReconsider);
                    if (StringUtils.isNotEmpty(dictionary.getItemCode())) {
                        jgJgxwPunishAction.setAdministrativeReconsider(dictionary.getItemCode());
                    }
                }
                //行政诉讼 xzss_status
                String administrativeAction = jgJgxwPunishAction.getAdministrativeAction();
                if (administrativeAction != null && !"".equals(administrativeAction)) {
                    Dictionary dictionary = dictionaryService.findCodeByTypeAndvalue("xzss_status", administrativeAction);
                    if (StringUtils.isNotEmpty(dictionary.getItemCode())) {
                        jgJgxwPunishAction.setAdministrativeAction(dictionary.getItemCode());
                    }
                }
                //结案情况—执行方式 jazxfs_status
                String casesClosedExecutionWay = jgJgxwPunishAction.getCasesClosedExecutionWay();
                if (casesClosedExecutionWay != null && !"".equals(casesClosedExecutionWay)) {
                    Dictionary dictionary = dictionaryService.findCodeByTypeAndvalue("jazxfs_status", casesClosedExecutionWay);
                    if (StringUtils.isNotEmpty(dictionary.getItemCode())) {
                        jgJgxwPunishAction.setCasesClosedExecutionWay(dictionary.getItemCode());
                    }
                }
                //结案情况—执行结果 jazxjg_status
                String casesClosedExecutionResult = jgJgxwPunishAction.getCasesClosedExecutionResult();
                if (casesClosedExecutionResult != null && !"".equals(casesClosedExecutionResult)) {
                    Dictionary dictionary = dictionaryService.findCodeByTypeAndvalue("jazxjg_status", casesClosedExecutionResult);
                    if (StringUtils.isNotEmpty(dictionary.getItemCode())) {
                        jgJgxwPunishAction.setCasesClosedExecutionWay(dictionary.getItemCode());
                    }
                }
                //来源 gjbm_status
                String cdSource = jgJgxwPunishAction.getCdSource();
                String cdSourceCode = dictionaryService.findCodeByTypeAndvalue("gjbm_status", cdSource).getItemCode();
                if (StringUtils.isNotEmpty(cdSourceCode)) {
                    jgJgxwPunishAction.setCdSource(cdSourceCode);
                }
            }
        }
        boolean b = jgJgxwPunishActionService.saveBatch(JgJgxwPunishActionEntities);
        return R.ok().put("jgJgxwPunishActionEntity",b);
    }

    @RequestMapping("/exportExcel")
    public void exportExcel (@RequestBody Map < String, Object > params, HttpServletRequest request){
        exportPunishActionService.exportPunishAction(params, request);
    }*/
}
